#pragma once
#include<iostream>
using namespace std;

#include<assert.h>

namespace mName
{
	template<class T>
	class vector
	{
	public:
		typedef T* iterator;
		typedef const T* const_iterator;

		iterator begin()
		{
			return _start;
		}

		iterator end()
		{
			return _finish;
		}

		size_t size() const
		{
			return _finish - _start;
		}

		size_t capacity() const
		{
			return _end_of_storage - _start;
		}

		vector()
			:_start(nullptr)
			, _finish(nullptr)
			, _end_of_storage(nullptr)
		{}

		void reserve(size_t n)
		{
			if (n > capacity())
			{
				T* tmp = new T[n];
				if(_start)
				{
					memcpy(tmp, _start, n * sizeof(T));
					delete[] _start;
				}
				_finish = tmp + size();
				_start = tmp;
				_end_of_storage = tmp + n;
			}
		}

		void push_back(const T& x)
		{
			//if (_finish == _end_of_storage)
			//{
			//	size_t newcapacity = capacity() == 0 ? 4 : capacity() + 1;
			//	reserve(newcapacity);
			//}
			//*_finish = x;
			//++_finish;
			iterator pos = insert(_finish, x);
		}

		T& operator[](size_t pos)
		{
			assert(pos < size());
			return _start[pos];
		}

		const T& operator[](size_t pos) const
		{
			assert(pos < size());
			return _start[pos];
		}

		iterator insert(iterator pos, const T& x)
		{
			assert(pos >= _start && pos <= _finish);

			size_t len = pos - _start;
			if (_finish == _end_of_storage)
			{
				size_t newcapacity = capacity() == 0 ? 4 : capacity() * 2;
				reserve(newcapacity);
			}
			pos = _start + len;
			T* end = _finish;
			while (end > pos)
			{
				*end = *(end - 1);
				//*(end + 1) = *end;
				end--;
			}
			*pos = x;
			++_finish;
			return pos;
		}

		void print()
		{
			assert(_start);
			for (auto v : *this)
			{
				cout << v << " ";
			}
			cout << endl;
		}

		~vector()
		{
			if (_start)
			{
				delete[] _start;
				_start = _finish = _end_of_storage = nullptr;
			}
		}

	private:
		iterator _start;
		iterator _finish;
		iterator _end_of_storage;
	};
};


